package com.yuanyi.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2019/8/26.
 */
public class StringUtil {
    public static String rstr(int i){
        return UUID.randomUUID().toString().replaceAll("-","").substring(0,i);
    }

    public static String getWechatURL(String url){
        String wurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cfb23748200cfe0&redirect_uri="+url
                +"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        return wurl;
    }


    public static String barCode(String str) throws WriterException, IOException {
                Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bm = qrCodeWriter.encode(str
                , BarcodeFormat.QR_CODE, 200, 200, hints);
        boolean isWin = System.getProperty("os.name").indexOf("Windows")>=0;
        String fn = UUID.randomUUID().toString()+".png";
        String fileName = "/uploadPic/"+fn;
        if(isWin){
            fileName = "E://Replair//uploadPic/"+fn;
        }
        MatrixToImageWriter.writeToStream(bm, "png",
                new FileOutputStream(fileName));
        return fn;
    }

    public static String sha1(String str){
        MessageDigest md = null;
        String tempStr = null;
        try
        {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            tempStr = byteToStr(digest);

            return tempStr;
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest = strDigest + byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private static String byteToHexStr(byte b) {
        char[] digit = {
                '0',
                '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E',
                'F' };

        char[] tempArr = new char[2];
        tempArr[0] = digit[(b >>> 4 & 0xF)];
        tempArr[1] = digit[(b & 0xF)];
        String s = new String(tempArr);
        return s;
    }
}
